using HengTong.Kingdee.EASLoginProxyService;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.ServiceModel;

namespace HengTong.Kingdee.Eas;

public class EasLogin(ILogger<EasLogin> logger, IMemoryCache memoryCache, IOptions<KingdeeEasOptions> options)
{

    private async Task<string> Login()
    {
        var username = options.Value.Username;
        var password = options.Value.Password;
        var sliName = options.Value.SliName;
        var dcName = options.Value.DcName;
        var language = options.Value.Language;
        var dbType = options.Value.DbType;
        var client = EASLoginProxyClient.CreateFromConfiguration();
        
        try
        {
            var result = await client.loginAsync(username, password, sliName, dcName, language, dbType);
            if (string.IsNullOrWhiteSpace(result?.loginReturn?.sessionId))
            {
                logger.LogError("EAS登录失败, 登录信息{@user}", options.Value);
                throw new Exception("EAS登录失败");
            }
            logger.LogInformation("EAS登录成功, {@user}", result.loginReturn);
            return result.loginReturn.sessionId;
        }
        catch (CommunicationException ex) when (ex.InnerException is HttpRequestException)
        {
            logger.LogError(ex, "EAS登录通讯故障, 登录信息{@user}", options.Value);
            throw;
        }
    }
    
    /// <summary>
    /// 获取登录Session
    /// </summary>
    /// <returns></returns>
    public async Task<string> GetSessionId()
    {
        var key = $"{nameof(EasLogin)}.{nameof(GetSessionId)}";
        var sessionId = await memoryCache.GetOrCreateAsync(key, async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
            return await Login();
        });
        // 如果 sessionId是空则说明登录失败了, 一定要移除缓存
        if(string.IsNullOrWhiteSpace(sessionId)) memoryCache.Remove(key);
        return sessionId;
    }
}